import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Jiang Jinxi
 * Date: 2024-09-02
 * Time: 12:15
 */
class MyThreadPool{
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
    private  int maxPoolSize = 0;
    private List<Thread> threadList = new ArrayList<>();
    //规定核心线程数和最大线程数
    public MyThreadPool(int corePoolSize, int maxPoolSize){
        this.maxPoolSize = maxPoolSize;
        //一次性创建corePoolSize个线程并启动
        for (int i = 0; i < corePoolSize; i++) {
            Thread thread = new Thread(() -> {
                try {
                    while(true){
                        Runnable runnable = queue.take();
                        runnable.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            thread.start();
            //启动后, 线程不会执行任务, 处于阻塞状态, 因为此时任务队列中还没有任务
            threadList.add(thread);
        }
    }

    public void submit(Runnable runnable){
        try {
            queue.put(runnable);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //这里是我们随便规定的, 如果超过八个线程, 就再创建线程
        if(threadList.size() >= 8 && threadList.size() <= maxPoolSize){
            Thread thread = new Thread(() -> {
                try {
                    while(true){
                        Runnable task = queue.take();
                        task.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            thread.start();
            threadList.add(thread);
        }
    }
}
public class Demo28 {
    public static void main(String[] args) {
        MyThreadPool myThreadPool = new MyThreadPool(10, 20);
        for(int i = 0; i < 1000; i++){
            int id = i;
            myThreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello " + id + " " + Thread.currentThread().getName());
                }
            });
        }
    }
}
